package controllers

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"fmt"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/sessions"
)

type Cancel struct {
	Ctx iris.Context
}

//取消收藏学校
func (c *Cancel) PostCancelCollege() interface{} {
	channel := c.Ctx.PostValue("channel")
	colledgeId := c.Ctx.PostValue("colledgeId")

	if channel == "" || colledgeId == "" {
		return utils.CommonRes(1000, fmt.Sprintf("参数有误"), "")
	}

	var userId int64
	if channel == "wechat" {
		token := c.Ctx.GetHeader("token")
		if token == "" {
			return utils.CommonRes(1000, fmt.Sprintf("token为空"), "")
		}

		claims, err := utils.ParseToken(token)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("解析token出错"), "")
		}

		userId = utils.Atoi64(claims.Id)
	} else {
		session := sessions.Get(c.Ctx)
		userId, _ = session.GetInt64(fmt.Sprintf("%s userId", channel))
	}

	//连接数据库
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("连接数据库出错: %s", err), "")
	}

	updateData := map[string]interface{}{
		"status": 0,
	}

	_, err = db.Table(new(models.CollectionCollege)).Where("user_id = ?", userId).Update(updateData)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据库有问题"), "")
	}

	return utils.CommonRes(20000, fmt.Sprintf("取消收藏成功"), "")
}

//取消收藏专业
func (c *Cancel) PostCancelMajor() interface{} {
	channel := c.Ctx.PostValue("channel")
	categoryId := c.Ctx.PostValue("categoryId")

	if channel == "" || categoryId == "" {
		return utils.CommonRes(1000, fmt.Sprintf("参数有误"), "")
	}

	var userId int64
	if channel == "wechat" {
		token := c.Ctx.GetHeader("token")
		if token == "" {
			return utils.CommonRes(1000, fmt.Sprintf("token为空"), "")
		}

		claims, err := utils.ParseToken(token)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("解析token出错"), "")
		}

		userId = utils.Atoi64(claims.Id)
	} else {
		session := sessions.Get(c.Ctx)
		userId, _ = session.GetInt64(fmt.Sprintf("%s userId", channel))
	}

	//连接数据库
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("连接数据库出错: %s", err), "")
	}

	updateData := map[string]interface{}{
		"status": 0,
	}

	_, err = db.Table(new(models.CollectionMajor)).Where("user_id = ?", userId).Update(updateData)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据库有问题"), "")
	}

	return utils.CommonRes(20000, fmt.Sprintf("取消收藏成功"), "")
}
